package com.jpxx.jpscp.admin.system.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jpxx.jpscp.admin.common.exception.ParameterException;
import com.jpxx.jpscp.admin.system.entity.Role;
import com.jpxx.jpscp.admin.system.entity.RoleAuthority;
import com.jpxx.jpscp.admin.system.mapper.RoleAuthorityMapper;
import com.jpxx.jpscp.admin.system.mapper.RoleMapper;
import com.jpxx.jpscp.admin.system.service.RoleService;
import com.jpxx.jpscp.core.base.service.serviceImpl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @author: Zhaopengfei
 * @copyright: 金鹏信息技术有限公司
 * @CreatedDate: 2018年03月14日 15:24
 * @Copyright: All rights Reserved，Designed By Jpsycn
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleAuthorityMapper roleAuthorityMapper;

    @Override
    public List<Role> getByUserId(String userId) {
        return roleMapper.selectByUserId(userId);
    }

    @Override
    public List<Role> list(boolean showDelete) {
        QueryWrapper<Role> wrapper = new QueryWrapper<Role>();
        if (!showDelete) {
            wrapper.eq("is_del", 0);
        }
        return roleMapper.selectList(wrapper.orderByAsc("create_date"));
    }

    @Override
    public boolean add(Role role) {
        return roleMapper.insert(role) > 0;
    }

    @Override
    public boolean update(Role role) {
        return roleMapper.updateById(role) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateState(String roleId, int isDelete) {
        if (isDelete != 0 && isDelete != 1) {
            throw new ParameterException("isDelete值需要在[0,1]中");
        }
        Role role = new Role();
        role.setId(roleId);
        role.setIsDel(isDelete);
        boolean rs = roleMapper.updateById(role) > 0;
        if (rs) {
            //删除角色的权限
            roleAuthorityMapper.delete(new QueryWrapper<RoleAuthority>().eq("role_id", roleId));
        }
        return rs;
    }

    @Override
    public Role getById(String roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public boolean delete(String roleId) {
        return roleMapper.deleteById(roleId) > 0;
    }
}
